import { existsSync, readFileSync, renameSync, writeFileSync } from "fs";
import { join } from "path";
import * as rimraf from 'rimraf';
import { cpDir } from "../utils/FileUtil";
import { PublishLaya2Base } from "./PublishLaya2Base";
/**bilibili发布 */
export class BiliPublish extends PublishLaya2Base {
    get projDir() { return "biligame" };
    get libJs() { return "laya.bilimini.js" };
    createProject() {
        let toPath = this.mProjPath
        if (existsSync(toPath)) {
            this.doPack();
            return;
        }
        this.log('创建项目目录:' + toPath);

        let tplPath = this.mTempProjPath
        rimraf(toPath, (err2) => {
            if (err2) {
                console.warn(`清理目录${toPath}出错`);
                return;
            }

            cpDir(tplPath, toPath, () => {
                let projCfgPath = join(toPath, 'game.json');
                let fstr = readFileSync(projCfgPath).toString();
                let content = JSON.parse(fstr);
                content.appId = this._publishVo.content.appId;
                writeFileSync(projCfgPath, JSON.stringify(content));

                this.log('项目生成完毕 下一步可以开始打包游戏了');
                this.doPack();
            });
        });
    }

    async doPack() {
        await this.buildProject();
        this._updateIndexJs();
        this.packOver();
    }

    async compressJs(jsList: string[], binPath: string, toPath: string) {
        await super.compressJs(jsList, binPath, toPath);
        let filePath = join(this.mProjPath, "index.js");
        if (!existsSync(filePath)) {
            return;
        }
        let fileContent = readFileSync(filePath, "utf8");
        for (let i = 0; i < jsList.length; i++) {
            let fileName = jsList[i];
            if(fileName.indexOf(".min.")!=-1){
                continue;
            }
            let arr = fileName.split(".");
            let fileType = arr.pop();
            let newName = arr.join(".") + ".min." + fileType;
            renameSync(join(toPath, jsList[i]), join(toPath, newName));
            let reg=new RegExp(fileName,"gm");
            fileContent = fileContent.replace(reg, newName);
        }
        writeFileSync(filePath, fileContent, "utf8");
    }

    private _updateIndexJs() {
        let filePath = join(this.mProjPath, "index.js");
        if (!existsSync(filePath)) {
            return;
        }
        let fileContent = readFileSync(filePath, "utf8");
        fileContent = fileContent.replace(/loadLib(\(['"])/gm, "require$1./");
        writeFileSync(filePath, fileContent, "utf8");
    }
}